import { defineStore } from 'pinia'
import chatApi from '@/apis/chat'

export const useChannelStore = defineStore('channel', {
  state: () => ({
    data: [],
    active: null,
    initialized: false,
  }),
  actions: {
    async init() {
      if (!this.initialized) {
        this.initialized = true
        await this.getData()
      }
    },
    async getData() {
      this.data = (await chatApi.channel.list()).data
      if (!this.active) {
        this.autoSwitch()
      }
    },
    switch(channel) {
      this.active = channel
      localStorage.setItem('channelId', channel.id)
    },
    autoSwitch() {
      if (this.data.length > 0) {
        //获取本地记录
        let channelId = parseFloat(localStorage.getItem('channelId') || 0)
        let channel = this.data.find((item) => item.id === channelId)
        if (!channel) channel = this.data[0]
        this.switch(channel)
      }
    },
  },
})
